# 用户模块专用的工具文件
from django.contrib.auth.backends import ModelBackend
import re
from apps.users.models import User
from itsdangerous import TimedJSONWebSignatureSerializer as Serialize,BadData
from django.conf import settings


def generate_verify_url(user):
    """对用户唯一标识信息进行序列化并生成验证链接"""
    s = Serialize(settings.SECRET_KEY,3600*24)
    data = {"user_id":user.id,"email":user.email}
    token = s.dumps(data).decode()

    # 生成验证链接
    # verify_url = "http://www.meiduo.site:8000/emails/verification/?token=" + token
    verify_url = settings.EMAIL_VERIFY_URL + "?token=" + token
    return verify_url


def check_verify_url(token):
    """
    从token中提取用户要激活邮箱的用户
    :param token: 激活连接中密文信息
    :return: user
    """
    s = Serialize(settings.SECRET_KEY,3600*24)
    try:
        data = s.loads(token)
    except BadData:
        return None
    else:
        # 提取token中的用户信息
        user_id = data.get("user_id")
        email = data.get("email")

        # 根据用户信息查询出对应的user
        try:
            user = User.objects.get(id=user_id,email=email)
        except User.DoesNotExist:
            return None
        else:
            return user


def get_user_by_account(account):
    """根据账号认证一个注册用户
        account: 账号: 用户名, 手机号
        :return user
    """
    #　前台登陆
    try:
        # 判断用户输入的账号是否是手机号
        if re.match(r"^1[3-9]\d{9}$", account):
            # 如果时手机号,就使用手机号去认证
            user = User.objects.get(mobile=account)
        else:
            # 　如果是用户名就使用用户名认证
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user

# UsernameMobileAuthBackend
class UsernameMobileAuthBackend(ModelBackend):
    '''
    自定义用户认证类
    '''
    def authenticate(self, request, username=None, password=None, **kwargs):
        """重写用户认证的方法
        在用户名认证的基础上,追加手机号的认证方式
        """
        # 通过request来判断,如果传入了request是前台登陆,反之后台登陆
        if request is None:
            # 后台登陆
            # 单独判断是否时is_superuser
            # is_staff 普通管理员
            # is_superuser 超级管理员
            try:
                user = User.objects.get(username=username, is_staff=True)
            except User.DoesNotExist:
                return None
            else:
                if user and user.check_password(password):
                    return user
        else:
            # 获取user
            user = get_user_by_account(username)

        # 认证结束后记得校验密码
        if user and user.check_password(password):
            return user
        else:
            return None